package com.seaboxdata.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitContUtil {
    private static ConnectionFactory connectionFactory;
    private static Connection conn;
    private static Channel channel;
    public static Channel getChannel(){
        if (channel!=null){
            synchronized (RabbitContUtil.class){
                if (channel!=null){
                    ConnectionFactory factory = new ConnectionFactory();
                    factory.setUsername("ytc");
                    factory.setPassword("ytc");
                    factory.setHost("172.21.17.51");
                    factory.setPort(5672);
                    //建立到代理服务器到连接
                    Connection conn = null;
                    try {
                        conn = factory.newConnection();
                        //获得信道
                        final Channel channel = conn.createChannel();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                        e.printStackTrace();
                    }

                }
            }
        }return channel;
    }
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("ytc");
        factory.setPassword("ytc");
        //设置 RabbitMQ 地址
        factory.setHost("172.21.17.51");
        //建立到代理服务器到连接
        Connection conn = factory.newConnection();
        //获得信道
        Channel channel = conn.createChannel();
        //声明交换器
        String exchangeName = "exchange";
        channel.exchangeDeclare(exchangeName, "direct", true);

        String routingKey = "wendao";
        //发布消息
        byte[] messageBodyBytes = "宜停车".getBytes();
        channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

        channel.close();
        conn.close();
    }
}
